package find_code.blockSearch;

//分块查找扩展，无规律，采取分块无交集的方式
public class BlockSearchExpand {
    public static void main(String[] args) {
        int[] arr = {27,22,30,40,36,
                13,19,16,20,
                7,10,
                43,50,48};

        BlockExpand blockExpand1 = new BlockExpand(22,40,0,4);
        BlockExpand blockExpand2 = new BlockExpand(13,20,5,8);
        BlockExpand blockExpand3 = new BlockExpand(7,10,9,10);
        BlockExpand blockExpand4 = new BlockExpand(43,50,11,13);

        BlockExpand[] blockExpands = {blockExpand1,blockExpand2,blockExpand3,blockExpand4};

        int number = 16;

        System.out.println(getIndex(arr, blockExpands, number));
    }

    //获取查找数字的索引
    public static int getIndex(int[] arr,BlockExpand[] blockExpands,int number){
        int blockExpandIndex = blockExpandIndex(blockExpands,number);
        if(blockExpandIndex == -1)
            return -1;
        int startIndex = blockExpands[blockExpandIndex].getStartIndex();
        int endIndex = blockExpands[blockExpandIndex].getEndIndex();
        for (int i = startIndex; i <= endIndex ; i++) {
            if(number == arr[i]){
                return i;
            }
        }
        return -1;
    }

    //获取查找数字所在的块的索引
    public static int blockExpandIndex(BlockExpand[] blockExpands,int number){
        for (int i = 0; i < blockExpands.length; i++) {
            if(number >= blockExpands[i].getMin() && number <= blockExpands[i].getMax()){
                return i;
            }
        }
        return -1;
    }
}
